package com.dayaokeji.rhythmschoolstudent.client.message;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;

import com.beetle.bauhinia.gallery.GalleryImage;
import com.dayaokeji.imkitwrapper.fragment.GroupMessageFragment;
import com.dayaokeji.imkitwrapper.fragment.MessageFragment;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.group.GroupMembersActivity;
import com.dayaokeji.rhythmschoolstudent.event.GroupEvent;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.GroupApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.Group;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

public class GroupChatActivity extends BaseActivity {

    private static final String EXTRA_GROUP_ID = "group_id";
    private static final String EXTRA_GROUP_NAME = "group_name";
    private static final String GROUP_CHAT_FRAGMENT_TAG = "group_chat";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private Fragment groupChatFragment;

    private long groupId;
    private String groupName;

    private UserApi userApi = ApiUtils.getApi(UserApi.class);
    private GroupApi groupApi = ApiUtils.getApi(GroupApi.class);
    private Call<ServerResponse<UserInfo>> userDetailCall;
    private Call<ServerResponse<Group>> selectGroupByIdCall;

    private Group group;

    public static void navigation(Context context,long groupId,String groupName) {
        if (context instanceof Activity) {
            Intent intent = new Intent(context, GroupChatActivity.class);
            intent.putExtra(EXTRA_GROUP_ID, groupId);
            intent.putExtra(EXTRA_GROUP_NAME, groupName);
            context.startActivity(intent);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_chat);
        setSupportActionBar(toolbar);
        EventBus.getDefault().register(this);
        init();
    }


    private void init() {
        Intent intent = getIntent();
        groupId = intent.getLongExtra(EXTRA_GROUP_ID, 0);
        groupName = intent.getStringExtra(EXTRA_GROUP_NAME);

        if (groupId == 0) {
            Logger.d("group id is 0");
            return;
        }

        setupView();
    }

    /**
     * toolbar 样式
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.group_chat, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_group_members:
                reqGroupInfo();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void reqGroupInfo() {
        selectGroupByIdCall = groupApi.selectGroupById(groupId);
        selectGroupByIdCall.enqueue(new ServerCallback<Group>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Group> response) {
                if (success) {
                    group = response.getBody();
                    if (group != null) {
                        GroupMembersActivity.navigation(GroupChatActivity.this,group);
                    }else{
                        ToastUtils.info("未获取到群组信息");
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void existAndDelGroupEvent(GroupEvent groupEvent) {
        ActivityStackManager.finish(this);
    }

    private void setupView() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(groupName);
        }
        groupChatFragment = getSupportFragmentManager().findFragmentByTag(GROUP_CHAT_FRAGMENT_TAG);
        if (groupChatFragment == null) {
            groupChatFragment = GroupMessageFragment.newInstance(UserUtils.getCurrentUid(), groupId);
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content, groupChatFragment).commit();

        addDisposable(Observable.interval(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (((GroupMessageFragment)groupChatFragment).refreshConnectState()) {
                    toolbar.setSubtitle("邀请码："+groupId);
                }else{
                    toolbar.setSubtitle("正在连接...");
                }
            }
        }));

        ((GroupMessageFragment)groupChatFragment).setImgPickerClickListener(new MessageFragment.ImgPickerClickListener() {
            @Override
            public void onClick(ArrayList<GalleryImage> galleryImages, int position) {
                GalleryActivity.navigation(GroupChatActivity.this, galleryImages, position);
            }
        });

        ((GroupMessageFragment) groupChatFragment).setUserInfoCallback(new MessageFragment.UserInfoCallback() {
            @SuppressLint("DefaultLocale")
            @Override
            public void callback(final long uid, final MessageFragment.GetUserCallback callback) {
                if (uid != 0) {
                    userDetailCall = userApi.userDetail(uid);
                    userDetailCall.enqueue(new ServerCallback<UserInfo>() {
                        @SuppressLint("DefaultLocale")
                        @Override
                        public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                            if (success) {
                                MessageFragment.User user = new MessageFragment.User();
                                user.uid = uid;
                                user.identifier = String.format("%d", uid);
                                if (response.getBody() != null) {
                                    UserInfo userInfo = response.getBody();
                                    user.name = userInfo.getName();
                                    user.identifier = userInfo.getName();
                                    user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                                }else{
                                    user.name = String.format("%d", uid);
                                    user.avatarURL = "";
                                }
                                Logger.d("callback user == "+user.toString());
                                if (!GroupChatActivity.this.isFinishing()) {
                                    callback.onUser(user);
                                }
                            }
                        }
                    });
                }else{
                    MessageFragment.User user = new MessageFragment.User();
                    user.uid = uid;
                    user.identifier = String.format("%d", uid);
                    UserInfo userInfo = UserUtils.getUserInfo();
                    if (userInfo != null) {
                        user.name = userInfo.getName() == null ? "" : userInfo.getName();
                        user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                    }
                    if (!GroupChatActivity.this.isFinishing()) {
                        callback.onUser(user);
                    }
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (selectGroupByIdCall != null) {
            selectGroupByIdCall.cancel();
        }
        if (userDetailCall != null) {
            userDetailCall.cancel();
        }
        EventBus.getDefault().unregister(this);
    }
}
